package com.yk103;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog.Calls;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

public class Wo3GFee extends Activity {
	private static final String EXCLUDE_NUMBER_SEP = ",";
	private final String SHARED_PREFERENCE_NAME = "Wo3GFee";
	private final String EXCLUDE_NUMBER_KEY = "ExcludeNumbers";
	private final String DURATION_OFFSET_KEY = "durationOffset";
	private final int BEG_DATE_PICKER_ID = 0;
	private final int END_DATE_PICKER_ID = 1;
	private final int ABOUT_DIALOG_ID = 2;
	private Button setBegDateButton, setEndDateButton, computeButton,
			addFreeCallButton, clearAllFreeCallButton;
	TextView begDateView, endDateView, resultView, freeCallTv;
	EditText freeCallNumbers, durationOffsetEt;
	CallDurationComputer cdc;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		cdc = new CallDurationComputer();
		InitWidgetsFromXml();
		loadSharedPerference();
		updateFreeCallTv();
	}

	public void InitWidgetsFromXml() {
		setBegDateButton = (Button) findViewById(R.id.begDateBtn);
		setBegDateButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(BEG_DATE_PICKER_ID);
			}
		});
		setEndDateButton = (Button) findViewById(R.id.endDateBtn);
		setEndDateButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(END_DATE_PICKER_ID);
			}
		});
		addFreeCallButton = (Button) findViewById(R.id.AddFreeCallBtn);
		addFreeCallButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (freeCallNumbers.getText() == null
						|| freeCallNumbers.getText().length() == 0) {
					return;
				} else {
					addToFreeCallList(freeCallNumbers.getText().toString());
					freeCallNumbers.setText("");
				}
			}
		});
		clearAllFreeCallButton = (Button) findViewById(R.id.delAllFreeCallBtn);
		clearAllFreeCallButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				clearFreeCallList();
			}
		});
		computeButton = (Button) findViewById(R.id.ComputeBtn);
		computeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				saveSharedPerference();
				StartCompute();
			}
		});

		begDateView = (TextView) findViewById(R.id.beginDateTv);
		begDateView.setText(cdc.getDateString(true));
		endDateView = (TextView) findViewById(R.id.endDateTv);
		endDateView.setText(cdc.getDateString(false));

		resultView = (TextView) findViewById(R.id.resultTv);
		freeCallNumbers = (EditText) findViewById(R.id.FreeCallsEt);
		freeCallTv = (TextView) findViewById(R.id.freeCallTv);
		durationOffsetEt = (EditText) findViewById(R.id.durationOffsetEt);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		int year, month, day;
		switch (id) {
		case BEG_DATE_PICKER_ID:
			year = cdc.getYear(true);
			month = cdc.getMonth(true);
			day = cdc.getDay(true);
			return new DatePickerDialog(this, begOnDateSetListener, year,
					month, day);
		case END_DATE_PICKER_ID:
			year = cdc.getYear(false);
			month = cdc.getMonth(false);
			day = cdc.getDay(false);
			return new DatePickerDialog(this, endOnDateSetListener, year,
					month, day);
		case ABOUT_DIALOG_ID:
			break;
		}
		return null;
	}

	private OnDateSetListener begOnDateSetListener = new OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			cdc.setYear(true, year);
			cdc.setMonth(true, monthOfYear);
			cdc.setDay(true, dayOfMonth);
			begDateView.setText(cdc.getDateString(true));
		}
	};

	private OnDateSetListener endOnDateSetListener = new OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			cdc.setYear(false, year);
			cdc.setMonth(false, monthOfYear);
			cdc.setDay(false, dayOfMonth);
			endDateView.setText(cdc.getDateString(false));
		}
	};

	private void clearFreeCallList() {
		cdc.freeCallNumbers.clear();
		saveSharedPerference();
		freeCallTv.setText("");
	}

	private void updateFreeCallTv() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < cdc.freeCallNumbers.size(); i++) {
			sb.append(cdc.freeCallNumbers.get(i));
			sb.append("\n");
		}
		freeCallTv.setText(sb.toString());
	}

	private void addToFreeCallList(String number) {
		boolean newNmmber = true;
		for (int i = 0; i < cdc.freeCallNumbers.size(); i++) {
			if (cdc.freeCallNumbers.get(i).equals(number)) {
				newNmmber = false;
			}
		}
		if (newNmmber) {
			cdc.freeCallNumbers.add(number);
			updateFreeCallTv();
			saveSharedPerference();
		}
	}

	private void StartCompute() {
		String durationStr = durationOffsetEt.getText().toString();
		if (durationStr == null || durationStr.trim().equals("")) {
			durationStr = Integer
					.toString(CallDurationComputer.DEF_DURATION_OFFSET);
			durationOffsetEt.setText(durationStr);
		}
		cdc.setDurationOffset(Integer.valueOf(durationStr));
		Cursor cursor = getContentResolver().query(Calls.CONTENT_URI, null,
				null, null, Calls.DEFAULT_SORT_ORDER);
		resultView.setText(getText(R.string.resultLabel)
				+ Integer.toString(cdc.compute(cursor))
				+ getText(R.string.inMinuteLabel));
	}

	private void loadSharedPerference() {
		String excludeNumbers;
		String duration;
		String[] numbers = null;
		SharedPreferences sp = getSharedPreferences(SHARED_PREFERENCE_NAME,
				MODE_PRIVATE);
		duration = sp.getString(DURATION_OFFSET_KEY, null);
		if (duration != null) {
			durationOffsetEt.setText(duration);
		}

		excludeNumbers = sp.getString(EXCLUDE_NUMBER_KEY, null);
		if (excludeNumbers != null) {
			numbers = excludeNumbers.split(",");
			for (int i = 0; i < numbers.length; i++) {
				cdc.freeCallNumbers.add(numbers[i]);
			}
		}
		updateFreeCallTv();
	}

	private void saveSharedPerference() {
		String excludeNumbers = "";
		String numberStr;
		String durationStr;
		SharedPreferences sp = getSharedPreferences(SHARED_PREFERENCE_NAME,
				MODE_PRIVATE);
		Editor editor = sp.edit();

		durationStr = durationOffsetEt.getText().toString();
		if (durationStr == null || durationStr.trim().equals("")) {
			durationStr = Integer
					.toString(CallDurationComputer.DEF_DURATION_OFFSET);
		}
		editor.putString(DURATION_OFFSET_KEY, durationStr);

		for (int i = 0; i < cdc.freeCallNumbers.size(); i++) {
			numberStr = cdc.freeCallNumbers.get(i);
			if (numberStr != null && false == numberStr.trim().equals("")) {
				excludeNumbers = excludeNumbers.concat(numberStr);
				excludeNumbers = excludeNumbers.concat(EXCLUDE_NUMBER_SEP);
			}
		}
		editor.putString(EXCLUDE_NUMBER_KEY, excludeNumbers);

		editor.commit();
	}
}
